/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.procurement.dao;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.javaeye.common.dto.DTO;
import com.javaeye.procurement.dto.MaterialsReceiveOrder;
import com.javaeye.procurement.web.SupplierCondition;
import com.javaeye.common.web.PageInfo;

public class MaterialsReceiveOrderDAOHibernate extends HibernateDaoSupport implements MaterialsReceiveOrderDAO {
	
	@SuppressWarnings("unchecked")
	public List getPageData(final DTO contidions, final PageInfo pageInfo) {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				int pageIndex = pageInfo.getPageIndex();
				int pageSize = pageInfo.getPageSize();
				SupplierCondition contidion = (SupplierCondition)contidions;
				Criteria crit = session.createCriteria(MaterialsReceiveOrder.class);
				
				Integer[] status = contidion.getStatus();
				if (status[0] != -1) {
					crit.add(Restrictions.in("status", status));
				}
				
				String contractNo = contidion.getContractNo().trim();
				if (!"".equals(contractNo)) {
					crit.add(Restrictions.like("contractNo", "%" + contractNo + "%"));
				}
				
				String name = contidion.getSupplierName().trim();
				if (!"".equals(name)) {
					crit.add(Restrictions.like("supplierName", "%" + name + "%"));
				}
				
				String orderId = contidion.getOrderId().trim();
				if (!"".equals(orderId)) {
					crit.add(Restrictions.like("id", orderId + "%"));
				}
				
				int skuId = contidion.getSkuId();
				if (skuId != -1) {
					crit.createAlias("orderDetails", "d")
					.add(Restrictions.eq("d.materialsId", skuId));
				}
				
				Date beginDate = contidion.getBeginDate();
				Date endDate = contidion.getEndDate();
				if (beginDate != null && endDate != null) {
					crit.add(Restrictions.between("realArriveDate", contidion.getBeginDate(), contidion.getEndDate()));
				}
				
				crit.addOrder(Order.desc("arriveDate"));
				
				crit.setProjection(Projections.rowCount());
				Integer rowNumber = (Integer)crit.uniqueResult();
				pageInfo.setCount(rowNumber);
				
				crit.setProjection(null);//取得了总数后,为了能够再次取得对象列表
				crit.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);//当hibernate采用关联的时候不使用这个返回的是个对象数组，加上这个返回的是当前列表的对象。
				crit.setFirstResult(pageIndex * pageSize);
				crit.setMaxResults(pageSize);
				return crit.list();
			}
		};
		return getHibernateTemplate().executeFind(action);
	}
	
	@SuppressWarnings("unchecked")
	public int getMaxOrderId(String orderIdSuff) {
		final String queryString = "select max(o.id) from MaterialsReceiveOrder o where o.id like ?";
		List result = getHibernateTemplate().find(queryString, orderIdSuff + "%");
		if (result.get(0) == null) {
			return 0;
		}
		String maxId = result.get(0).toString();
		maxId = maxId.replace(orderIdSuff, "");
		return Integer.parseInt(maxId);
	}
	
	@Override
	public void saveMaterialsReceiveOrder(MaterialsReceiveOrder order) {
		getHibernateTemplate().saveOrUpdate(order);
	}

	@Override
	public MaterialsReceiveOrder getMaterialsReceiveOrder(String orderId) {
		MaterialsReceiveOrder rOrder = (MaterialsReceiveOrder)getHibernateTemplate().get(MaterialsReceiveOrder.class, orderId);
		//由于使用延迟加载，这里需要强制取出关联集合
		Hibernate.initialize(rOrder.getOrderDetails());
		return rOrder;
	}
	
	/**
	 * 删除收货单
	 * @param orderId
	 */
	public void removeReceiveOrder(String orderId) {
		Object o = getHibernateTemplate().load(MaterialsReceiveOrder.class, orderId);
		getHibernateTemplate().delete(o);
	}
	
	/**
	 * 根据采购订单返回对应的收货单数
	 * @param supplierOrderId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public long getMaterialsReceiveOrderCount(String supplierOrderId) {
		final String queryString = "select count(o.id) from MaterialsReceiveOrder o where o.supplierOrderId=?";
		List result = getHibernateTemplate().find(queryString, supplierOrderId);
		long count = 0;
		if (result.size() > 0) {
			count = (Long)result.get(0);
		}
		return count;
	}

}
